package com.xxxx.comment.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.xxxx.comment.entity.dto.Result;
import com.xxxx.comment.service.FileStorageService;
import com.xxxx.comment.utils.SystemConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {

    @Resource(type = FileStorageService.class)
    private FileStorageService fileStorageService;

    @PostMapping("/blog")
    public Result uploadImage(@RequestParam("file") MultipartFile image) {
        // try {
        //     // 获取原始文件名称
        //     String originalFilename = image.getOriginalFilename();
        //     // 生成新文件名
        //     String fileName = createNewFileName(originalFilename);
        //     // 保存文件
        //     image.transferTo(new File(SystemConstants.IMAGE_UPLOAD_DIR, fileName));
        //     // 返回结果
        //     log.debug("文件上传成功，{}", fileName);
        //     return Result.ok(fileName);
        // } catch (IOException e) {
        //     throw new RuntimeException("文件上传失败", e);
        // }
        return fileStorageService.upload(image);
    }

    @GetMapping("/blog/delete")
    public Result deleteBlogImg(@RequestParam("name") String filename) {
        // 删除图片
        File file = new File(SystemConstants.IMAGE_UPLOAD_DIR, filename);
        if (file.isDirectory()) {
            return Result.fail("错误的文件名称");
        }
        FileUtil.del(file);
        return Result.ok();
    }

    private String createNewFileName(String originalFilename) {
        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        // 生成目录
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String fileName = UUID.randomUUID().toString();
        // 判断目录是否存在
        File dir = new File(SystemConstants.IMAGE_UPLOAD_DIR, StrUtil.format("/blogs/{}", date));
        if (!dir.exists()) {
            if (!dir.mkdirs())
                log.error("创建目录：{}/blogs/{} 失败！", SystemConstants.IMAGE_UPLOAD_DIR, fileName);
        }
        // 生成文件名
        return StrUtil.format("/blogs/{}/{}.{}", date, fileName, suffix);
    }

}
